package net.borlis.sample.service.repositories.common;

import net.borlis.sample.service.entities.common.ChangeType;
import net.borlis.sample.service.entities.common.Constants;
import net.borlis.sample.service.entities.common.IEntity;

import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.persistence.PersistenceException;
import java.util.Calendar;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * @author alex@borlis.net on 4/14/2014.
 */
@RequestScoped
public abstract class DynamixRepository<T extends IEntity> extends AbstractDynamixRepository<T> implements IDynamixRepository<T> {

    private static final String ERROR_LOG = "changed by field must be there";

    @Inject
    private Logger logger;


    @Override
    public T create(T t)  {
        if (t.getChangedBy() == null) {
            throw new PersistenceException(ERROR_LOG);
        }
        t.setChangedBy(t.getChangedBy());
        t.setChangedOn(Calendar.getInstance().getTime());
        t.setChangedType(ChangeType.I);
        t.setLocked(Constants.UNLOCKED);
        super.create(t);
        logger.log(Level.FINE, "The " + t + " created.");
        return t;
    }

    @Override
    public T update(T t) {
        if (t.getChangedBy() == null) {
            throw new PersistenceException(ERROR_LOG);
        }
        t.setChangedBy(t.getChangedBy());
        t.setChangedOn(Calendar.getInstance().getTime());
        t.setChangedType(ChangeType.U);
        t.setLocked(Constants.UNLOCKED);
        return super.update(t);
    }

}
